<template>
  <div>
    <el-container>
      <el-header
        style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;"
      >
        <div>
          <svg-icon class="primary" :icon-class="$route.meta.icon" />
          <span class="primary">批量发货</span>
        </div>
      </el-header>
      <div class="pd10">
        <div style="align-items: center;margin: 10px; margin-left: 20px">
         <div style="display: flex">
              <el-date-picker
                style="margin-right: 20px"
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
              <el-select v-model="supplierName" @change="changeSupp" placeholder="请选择供应商" value-key="id"
                         clearable filterable :filter-method="remoteMethod" style="width: 200px;margin-right: 20px;">
                <el-option v-for="(item,index) in suppliers"   style="width: 600px" :label="item.name" :value="item" :key="item.id">
                  <div style="display: flex">
                    <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                    <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toSearchSupplier">搜索供应商</div>
                </div>
                <div style="height: 30px"></div>
              </el-select>
              <ExportList2Excel ref="exportList2Excel" @handleExport="handleExport" name="下载发货单表" />
              <el-popover
                placement="bottom"
                title="温馨提示"
                width="200"
                trigger="manual"
                :content="popoverContent"
                v-model="popoverVisible"
              >
                <el-button
                  style="margin-left: 10px"
                  icon="el-icon-refresh-right"
                  type="primary"
                  @click="daoruClick"
                  slot="reference"
                >上传发货表</el-button>
              </el-popover>
          </div>

        </div>
        <el-table :data="memberData" border stripe ref="table" style="width: 100%;">
          <el-table-column label="信息提示" align="center" prop="errMsg"></el-table-column>
          <el-table-column label="编号" align="center" prop="id"></el-table-column>
          <el-table-column label="订单号" align="center" prop="orderSn" width="120"></el-table-column>
          <el-table-column label="送货单号" align="center" prop="sn" width="120"></el-table-column>
          <el-table-column label="送货日期" align="center" prop="orderDate"></el-table-column>
          <el-table-column label="货号/条码" align="center" prop="productSn" width="100"></el-table-column>
          <el-table-column label="商品名称" align="center" prop="name" min-width="100"></el-table-column>
          <el-table-column label="规格" align="center" prop="spec" width="100"></el-table-column>
          <el-table-column label="单位" align="center" prop="unit" width="50"></el-table-column>
          <el-table-column label="供应商" align="center" prop="supplierName" width="100"></el-table-column>
          <el-table-column label="数量" align="center" prop="quantity" width="80"></el-table-column>
          <el-table-column label="物流单号" align="center" prop="trackingNo" min-width="100"></el-table-column>
          <el-table-column label="收货人" align="center" prop="consignee" width="100"></el-table-column>
          <el-table-column label="联系电话" align="center" prop="phone" width="110"></el-table-column>
          <el-table-column label="地址" align="center" prop="address" width="100"></el-table-column>
          <el-table-column label="客户备注" align="center" prop="memo" min-width="100"></el-table-column>
          <el-table-column label="送货说明" align="center" prop="shippingMemo" min-width="100"></el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <el-row :gutter="24" style="margin-bottom: 10px">
          <el-button
            style="margin-left: 10px"
            icon="el-icon-refresh-right"
            type="primary"
            :loading="clicked"
            @click="updateClick"
          >确认发货</el-button>
        </el-row>
      </el-footer>
      <upload-excel-component
        ref="upload"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      />
    </el-container>
    <el-dialog
      title="查找供应商"
      :visible.sync="supplierVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="supplierClose">
      <div style="position: relative;height: 63vh;overflow: auto">
        <supplierTable :key="times"  @doubleSupplier="doubleSupplier"></supplierTable>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import supplierTable from "@/components/SupplierTable/supplierList"
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import {EventBus} from '@/api/eventBus'
  import {dateFormatter} from '@/filters/index'
  import UploadExcelComponent from "@/components/UploadExcel/index.vue";
  import ExportList2Excel from "@/components/ExportList2Excel";
  import {exportList,batchShipping} from '@/api/shipping'
  import { list as supplierList } from '@/api/supplier'
  export default {
    name: 'shipping-employeeAdd',
    directives: {elDragDialog },
    components:{ExportList2Excel,UploadExcelComponent,supplierTable},
    created() {
        this.loadSupplier('')
    },
    data(){
      return{
        tables:[],
        shippingStatus:1,
        times:'',
        checkTableDataLock: false, //表格数据检验的锁，前端检验成功后解锁
        daoruType: false,
        supplierVisible:false,
        daoruData: "",
        query: {
          date: [],
          supplierId:'',
        },
        supplierName:'',
        firstSheetName: "",
        memberData: [],
        suppliers:[],
        clicked: false, //防止双击
        popoverContent: "", //弹窗提示的内容
        popoverVisible: false, //导入检验成功后的弹窗提示
        pickerOptions: {//时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      }
    },
    methods:{
      loadSupplier(query){
        let params=new URLSearchParams()
        params.append('name',query)
        supplierList(params).then(res=>{
          this.suppliers=res.data.data
        })
      },
      doubleSupplier(data){
        this.supplierName=data.name
        this.query.supplierId=data.id
        this.supplierVisible=false
      },
      supplierClose(){
        this.supplierVisible=false
      },
      updateClick(){
        var _this=this
        this.clicked=true
        if (this.memberData.length>0){
          batchShipping(this.memberData).then(res=>{

            if (res.data.errorNum>0){
              _this.clicked=false
              this.memberData=res.data.itemList
              alert("存在错误，请检查输入表格")
            }else if (res.data.errorNum==0){
              _this.clicked=false
              EventBus.$emit('shipping-view', null)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/shipping/kdList'
                })
              })// 关闭当前tab回到列表
            }
          }).catch(error=>{
            _this.clicked=false
          })
        }else{
          alert("请上传表格")

            this.clicked=false


        }

      },
      toSearchSupplier(){
        this.times=new Date().getSeconds()
        this.supplierVisible=true
      },
      remoteMethod(query){
        this.loadSupplier(query)
      },
      changeSupp(val){
        this.supplierName=val.name
        this.query.supplierId=val.id
      },
      //下载模板的函数
      handleExport() {
        let _this= this
        //要导出函数携带的参数
        //要导出函数携带的参数
        let data ={}
        // data.tHeader = ["商品编号","地址","收货人","商品名称","联系电话","货号条码","数量","送货单号","规格","物流单号","单位"]
        data.tHeader = ["编号","送货日期","订单号","送货单号","货号条码","商品名称","规格","单位",'供应商',"数量","结算单价","物流单号","收货人","联系电话","地址","客户备注","送货说明","姓名","身份证号"]
        // data.filterVal = ["id","address","consignee","name","phone","productSn","quantity","sn","spec","trackingNo","unit"]
        data.filterVal = ["id","orderDate","orderSn","sn","productSn","name","spec","unit",'supplierName',"quantity","cost","trackingNo","consignee","phone","address","memo","shippingMemo","personalName","IdNumber"]
        data.filename = "送货列表";
        let params = new URLSearchParams();
        if(this.query.date.length > 0){
          params.append('startDate', this.query.date[0]);
          params.append('endDate', this.query.date[1]);
        }
        params.append('supplierId',_this.query.supplierId)
        params.append("shippingStatus", _this.shippingStatus);
        params.append("pageSize", 30000);
        exportList(params).then(response => {
          if(response.data.data.length > 0){
            response.data.data.map(item =>{
              item.orderDate = dateFormatter(item.orderDate)
            })
          }
          this.tables = response.data.data
          console.info("response.data.data--"+JSON.stringify(response.data.data))
          data.list = this.tables;
          _this.$refs.exportList2Excel.handleDownload(data)
          _this.total = response.data.total
        }).catch(error => {
          _this.$refs.exportList2Excel.unlockLoading()
          console.log('error!!')
        });
        this.$refs.exportList2Excel.handleDownload(data);
      },
      daoruClick(){
        this.$refs.upload.handleUpload();
      },
      //导入表单成功回调事件
      handleSuccess({ results, header, firstSheetName }) {

        this.memberData=[]
        let _this = this;
        let matchInfo = [
          { label: "编号", value: "id" },
          { label: "送货日期", value: "orderDate" },
          { label: "订单号", value: "orderSn" },
          { label: "送货单号", value: "sn" },
          { label: "货号条码", value: "productSn" },
          { label: "商品名称", value: "name" },
          { label: "规格", value: "spec" },
          { label: "单位", value: "unit" },
          { label: "供应商", value: "supplierName" },
          { label: "数量", value: "quantity" },
          { label: "地址", value: "address" },
          { label: "收货人", value: "consignee" },
          { label: "联系电话", value: "phone" },
          { label: "物流单号", value: "trackingNo" },
          { label: "客户备注", value: "memo" },
          { label: "送货说明", value: "shippingMemo" },
          { label: "姓名", value: "personalName" },
          { label: "身份证号", value: "IdNumber" },

        ];
          results.forEach( item=> {
            if (item.编号!=''||item.编号!=null){
              var batchData = {
                id:item.编号,
                orderSn:item.订单号,
                sn:item.送货单号,
                orderDate:item.送货日期,
                productSn:item.货号条码,
                name:item.商品名称,
                spec:item.规格,
                unit:item.单位,
                supplierName:item.供应商,
                quantity:item.数量,
                address :item.地址,
                consignee:item.收货人,
                phone:item.联系电话,
                trackingNo:item.物流单号,
                memo:item.客户备注,
                shippingMemo:item.送货说明,
                personalName:item.姓名,
                IdNumber:item.身份证号,
              };
              _this.memberData.push(batchData)

            }
        })


        // let matchResults = [];
        // let origenalResult = [];
        // if (results.length > 0) {
        //   results.map(item => {
        //     let matchResultsItem = {};
        //     let origenalResultItem = {};
        //     // origenalResultItem.errorMsg = "";
        //     matchInfo.map(matchInfoItem => {
        //       if (item[matchInfoItem.label]) {
        //         matchResultsItem[matchInfoItem.value] = item[matchInfoItem.label];
        //         origenalResultItem[matchInfoItem.value] =
        //           item[matchInfoItem.label];
        //       } else {
        //         matchResultsItem[matchInfoItem.value] = "";
        //         origenalResultItem[matchInfoItem.value] = "";
        //       }
        //       if (matchInfoItem.value == "vip") {
        //         matchResultsItem.vip = this.watchVip(matchResultsItem.vip);
        //       }
        //     });
        //     matchResults.push(matchResultsItem);
        //     origenalResult.push(origenalResultItem);
        //   });
        // }
        // // origenalResult = _this.checkTableData(
        // //   _this,
        // //   matchResults,
        // //   origenalResult
        // // );
        // //   console.info("_this.checkTableDataLock--"+_this.checkTableDataLock)
        // if (_this.checkTableDataLock == false) {
        //   _this.memberData = origenalResult;
        // } else {
        //   let number = matchResults.length;
        //   _this.popoverContent =
        //     "一共导入" + number + "条记录，请点击下方的确认提交";
        //   _this.popoverVisible = true;
        //   this.firstSheetName = firstSheetName;
        //   this.daoruData = matchResults;
        //   this.daoruType = true;
        // }
        //
        // console.log(
        //   "获取的导入结果matchResults--" + JSON.stringify(matchResults)
        // );
        // console.log(
        //   "获取的导入结果origenalResult--" + JSON.stringify(origenalResult)
        // );

        // console.log("获取的表头信息header--" + header)
        // console.log("获取的表头信息firstSheetName--" + firstSheetName)

      },
      // //名单导入
      beforeUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (isLt1M) {
          return true;
        }
        this.$message({
          message: "Please do not upload files larger than 1m in size.",
          type: "warning"
        });
        return false;
      },
    }
  }
</script>

<style scoped>
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
</style>
